module datelog;

import std.string, std.file, std.datetime;
import file;


class CDateLog : CFile
{
	private string m_szInitial;
	private string m_szDir;
	private string m_szFilePath;

	private SysTime m_sysTime;

	public this()
	{
		m_szInitial = null;
		m_szDir = null;
		m_szFilePath = null;
	}

	public ~this()
	{
	}

	public bool Create( const char[] pInitial, const char[] pDir = null )
	{
		m_szInitial = pInitial.idup;
		m_szDir = pDir.idup;

		if ( CreateLogFile() == false )
			return false;

		return true;
	}
	
	public bool AddLog( const char[] pText, bool bWithCRLF = true )
	{
		SysTime sysTime = Clock.currTime();

		if ( m_sysTime.year != sysTime.year	||
			 m_sysTime.month != sysTime.month	||
			 m_sysTime.day != sysTime.day )
		{
			Close();

			if ( CreateLogFile() == false )
				return false;
		}

		const char[] szTmp = format ( "%.2d:%.2d:%.2d ", 
			sysTime.hour, sysTime.minute, sysTime.second );
		
		int nWriteLen = 0;
		nWriteLen += Write( szTmp, szTmp.length );
		nWriteLen += Write( pText, pText.length );

		if ( bWithCRLF )
			nWriteLen += Write( "\r\n", ( "\r\n" ).length );

		Flush();

		return (nWriteLen > 0) ? true : false;
	}

	public bool CreateLogFile()
	{
		m_sysTime = Clock.currTime();

		if ( m_szDir.length )
		{
			if ( !exists( m_szDir ) )
				mkdir ( m_szDir );
			//	if ( !CreateDirectory( m_szDir, NULL ) )
			//		return false;

			if ( m_szDir[ m_szDir.length - 1 ] == '/' )
			{
				m_szFilePath = format( "%s%s%.4d%.2d%.2d.log", 
					m_szDir, m_szInitial, 
					m_sysTime.year, m_sysTime.month, m_sysTime.day );
			}
			else
			{
				m_szFilePath = format( "%s/%s%.4d%.2d%.2d.log",
					m_szDir, m_szInitial, 
					m_sysTime.year, m_sysTime.month, m_sysTime.day );
			}
		}
		else
		{
			m_szFilePath = format( "%s%.4d%.2d%.2d.log", 
				m_szInitial, 
				m_sysTime.year, m_sysTime.month, m_sysTime.day );
		}

		return Open( m_szFilePath, "ab" );
	}
	
	public @property string getFilePath() const
	{
		return m_szFilePath;
	}
}